package com.gem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gem.entity.User;
import com.gem.entity.UserAddress;
import com.gem.service.UserAddressService;
import com.gem.service.UserService;
import com.gem.util.ZhenziUtil;
import com.zhenzi.sms.ZhenziSmsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author 刘聪
 * Created  on 2020/12/16
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("User")
@Slf4j
public class UserController {
    private ZhenziSmsClient client = new ZhenziSmsClient(
            ZhenziUtil.apiUrl, ZhenziUtil.appId, ZhenziUtil.appSecret);

    @Autowired
    private UserService userService;

    @Autowired
    private UserAddressService addressService;

    @Value("${images}")
    private String targetPath;

    /**
     * 用户主页
     */
    @GetMapping("/index")
    public String index() {
        return "/user/index";
    }

    /**
     * 获取验证码
     * @param phone
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/getCode")
    @ResponseBody
    public String getCode(String phone, HttpSession session) throws Exception {
        //查看剩余短信条数
//        System.out.println("短信余额："+ client.balance());
        Map<String, Object> params = new HashMap<String, Object>();
//        接收者手机号
        params.put("number", phone);
//        短信模板ID
        params.put("templateId", "2023");
        //短信模板参数  测试网站注册验证码：{1}，{2}内有效
        String[] templateParams = new String[2];
        //模板中第一个参数  验证码  随机
        Integer r = new Random().nextInt(90000) + 10000;
        String code = r + "";
        templateParams[0] = code;
        templateParams[1] = "60秒";
        params.put("templateParams", templateParams);
        // 后期 处理
        session.setAttribute("sendCode", code);
        String result = client.send(params);
        return result;
    }

    /**
     * 注册
     *
     * @param phone
     * @param password
     * @param code
     * @param session
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Integer register(String phone, String password, String code, HttpSession session) {
//        System.out.println(phone);
//        System.out.println(password);
        Object sendCode = session.getAttribute("sendCode");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        User one = userService.getOne(wrapper);

//        System.out.println(sendCode + "--" + code);
        if (one != null) {
            return 0;
        } else {
            userService.save(one);
            return 1;
        }
    }

    /**
     * 登入
     *
     * @param username
     * @param password
     * @param session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Integer login(String username, String password, HttpSession session) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("username", username);
        wrapper.eq("password", password);
        User user = userService.getOne(wrapper);
        if (user != null) {
            session.setAttribute("User", user);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 退出
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();

        return "login";
    }

    /**
     * 修改个人资料
     * @return
     */
    @GetMapping("/information")
    public String information() {
        return "user/information";
    }

    @PostMapping("/information")
    @ResponseBody
    public String editInformation(User user) {
        userService.updateById(user);
        return "user/index";
    }

    //    实现图片文件上传
    @RequestMapping("/uploaduimg")
    public String upload(MultipartFile imgfile, Model model) throws IOException {
        String fileName = "";
//        获取后缀名
        fileName = imgfile.getOriginalFilename();//包含上传文件的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
//        文件重命名
        fileName = UUID.randomUUID().toString().replace("-", "").toLowerCase() + suffix;
        imgfile.transferTo(new File(targetPath, fileName));
        model.addAttribute("Img", fileName);
        return "user/information";
    }


    @GetMapping("/address")
    public String address(HttpSession session, Model model) {
        User user = (User) session.getAttribute("User");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", user.getId());
        List<UserAddress> addressList = (List<UserAddress>) addressService.list(wrapper);
        model.addAttribute("addressList", addressList);
        return "/user/address";
    }

    @PostMapping("/address")
    public String address(UserAddress userAddress) {
        addressService.save(userAddress);
        return "redirect:/user/address";
    }

    /**
     * 删除用户地址
     * @param id
     */
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        addressService.removeById(id);
        return "redirect:/user/address";
    }

    @GetMapping("/edit")
    public String findAddress(Integer id, Model model) {
        UserAddress address = addressService.getById(id);
        model.addAttribute("address", address);
        return "user/edit";
    }

    @PostMapping("/edit")
    public String editAddress(UserAddress address) {
        addressService.updateById(address);
        return "redirect:/user/address";
    }
}
